package com.xidian.zhiancloud.util.zyf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 * @Author: Summerless
 * @Date: 2021/5/2 13:39
 */
@Component
public class RedisUtil {

    @Autowired
    RedisTemplate redisTemplate;

    public String generateWorkId(Long companyId, Long departmentId) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(String.format("%06d", companyId));
        stringBuffer.append(String.format("%08d", departmentId));
        stringBuffer.append(getToday());
        String key = stringBuffer.toString();
        RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        long num = counter.incrementAndGet();
        counter.expireAt(getTodayEndTime());
        stringBuffer.append(String.format("%06d", num));
        return stringBuffer.toString();
    }

    public Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }
    public static String getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }
}
